﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Machine.Entity;
using Machine.Bussiness;
using System.Linq.Expressions;
using Microsoft.AspNetCore.Authorization;
using Machine.Model.ConfigModel;
using System.IO;

// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace Machine.Controllers
{
    /// <summary>
    /// 报修记录
    /// </summary>
    [Route("api/[controller]")]
    [Authorize(Roles = "Admin")]
    public class MachineWXController : Controller
    {
        /// <summary>
        /// 保存图片委托
        /// </summary>
        /// <param name="guid">guid</param>
        /// <param name="filePath">路径</param>
        /// <param name="fileName">文件名</param>
        /// <param name="uid">用户ID</param>
        /// <returns></returns>
        private delegate void SaveFileEventHandler(string guid, string filePath, string fileName, string uid);
        private MachineWXBLL BLL = new MachineWXBLL();
        private AttachmentListBLL SaveFileBLL = new AttachmentListBLL();
        /// <summary>
        /// 添加报修
        /// </summary>
        /// <param name="entity">报修</param>
        /// <returns></returns>
        [HttpPost]
        [Route("Add")]
        public JsonResult Add([FromBody]MachineBX entity = null)
        {
            if (entity == null)
                return Json(new { recode = 0, MissingFieldException = "参数为空" });

            string uid = Request.Headers["Uid"].ToString();
            string role = Request.Headers["Dept"].ToString();
            string kindPath = "RoleKindMap:" + role;
            string kind = BaseConfigModel.Configuration[kindPath];
            string guid = Guid.NewGuid().ToString();
            string wxid = BLL.getNextSeq(kind);
            //绑定委托
            SaveFileEventHandler mySaveFile = new SaveFileEventHandler(SaveFileBLL.SaveFile);

            //处理图片
            string webRootPath = BaseConfigModel.WebRootPath;
            string imgs = entity.Img;
            if (imgs != null && imgs != "")
            {
                string[] imgArray = imgs.Split('^');
                int i = 0;
                foreach (string img in imgArray)
                {
                    string filePath = webRootPath + "/" + img;
                    mySaveFile.Invoke(guid, filePath, wxid + "-" + i.ToString() + "jpg", uid);
                    i++;
                }
            }

            entity.kind = kind;
            entity.WXID = wxid;
            entity.Appliant = uid;
            entity.AppTime = DateTime.Now;

            entity.Del = false;
            entity.Creater = uid;
            entity.CreateTime = DateTime.Now;
            entity.Updater = uid;
            entity.Updatetime = DateTime.Now;
            entity.Status = "10";
            entity.GUID = guid;

            if (BLL.Add(entity))
            {
                return Json(new { recode = 1, msg = "新增成功" });
            }
            return Json(new { recode = 0, msg = "新增失败" });
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("upload")]
        public async Task<JsonResult> upload()
        {
            string webRootPath = BaseConfigModel.WebRootPath;
            string fileRootPath = BaseConfigModel.Configuration["FilePath"];
            string newFileName = System.Guid.NewGuid().ToString() + ".jpg"; //随机生成新的文件名
            var folderPath = webRootPath + fileRootPath;
            var filePath = webRootPath + fileRootPath + "/" + newFileName;

            try
            {
                if (!Directory.Exists(folderPath))
                {
                    Directory.CreateDirectory(folderPath);
                }

                FileStream fileStream = new FileStream(filePath, FileMode.CreateNew);
                //每次读取1024
                int num = 1024;
                byte[] buffer = new byte[num];
                int readByte = 0;
                while ((readByte = await Request.Body.ReadAsync(buffer, 0, num)) != 0)
                {
                    fileStream.Write(buffer, 0, readByte);
                }
                // var buffer = new byte[Convert.ToInt32(Request.ContentLength)];
                // await Request.Body.ReadAsync(buffer, 0, buffer.Length);
                // fileStream.Write(buffer, 0, buffer.Length);
                fileStream.Close();

                return Json(new { recode = 1, msg = "上传成功", filePath = fileRootPath + "/" + newFileName });
            }
            catch
            {

            }
            return Json(new { recode = 0, msg = "上传失败" });
        }

        /// <summary>
        /// 保修员查询查询报修
        /// </summary>
        /// <param name="para">json</param>
        /// <returns></returns>
        [HttpPost]
        [Route("getList")]
        public JsonResult getList([FromBody]Newtonsoft.Json.Linq.JObject para)
        {
            string status;
            int pageIndex = 1, pageSize = 10;
            bool aboutMe = false;
            status = para["status"].ToString();
            pageIndex = Convert.ToInt32(para["pageIndex"]);
            pageSize = Convert.ToInt32(para["pageSize"]);
            aboutMe = Convert.ToBoolean(para["aboutMe"]);

            string uid = Request.Headers["Uid"].ToString();
            string role = Request.Headers["Dept"].ToString();
            string recid = "0";
            if (aboutMe)
            {
                recid = uid;
            }
            return Json(BLL.GetPageList(role, uid, status, pageIndex, pageSize, recid));
        }

        /// <summary>
        /// 根据wxid查询
        /// </summary>
        /// <param name="para">json</param>
        /// <returns></returns>
        [HttpPost]
        [Route("getInfo")]
        public JsonResult getMachineWXByID([FromBody]Newtonsoft.Json.Linq.JObject para)
        {
            string wxid = para["wxid"].ToString();
            return Json(BLL.getMachineWX(wxid));
        }

        /// <summary>
        /// 根据关键词查询
        /// </summary>
        /// <param name="para">json</param>
        /// <returns></returns>
        [HttpPost]
        [Route("getListByKey")]
        public JsonResult getListByKey([FromBody]Newtonsoft.Json.Linq.JObject para)
        {
            string key;
            int pageIndex = 1, pageSize = 10;
            bool aboutMe = false;
            key = para["key"].ToString();
            pageIndex = Convert.ToInt32(para["pageIndex"]);
            pageSize = Convert.ToInt32(para["pageSize"]);
            aboutMe = Convert.ToBoolean(para["aboutMe"]);

            string uid = Request.Headers["Uid"].ToString();
            string recid = "0";
            if (aboutMe)
            {
                recid = uid;
            }
            return Json(BLL.getListByKey(key, recid, pageIndex, pageSize));
        }

        /// <summary>
        /// 查询删除信息
        /// </summary>
        /// <param name="para">json</param>
        /// <returns></returns>
        [HttpPost]
        [Route("getDelList")]
        public JsonResult getDelList([FromBody]Newtonsoft.Json.Linq.JObject para)
        {
            int pageIndex = 1, pageSize = 10;
            pageIndex = Convert.ToInt32(para["pageIndex"]);
            pageSize = Convert.ToInt32(para["pageSize"]);
            string dept = Request.Headers["Dept"].ToString();
            if (dept != "3")
            {
                return Json(new { recode = 0, msg = "非管理员不能删除" });
            }

            return Json(BLL.getDelList(pageIndex, pageSize));
        }

        /// <summary>
        /// 更新维修状态
        /// </summary>
        /// <param name="para">json</param>
        /// <returns></returns>
        [HttpPost]
        [Route("updateStatus")]
        public JsonResult updateStatus([FromBody]Newtonsoft.Json.Linq.JObject para)
        {
            string wxid, status, context;
            wxid = para["wxid"].ToString();
            status = para["status"].ToString();
            context = para["context"].ToString();

            string uid = Request.Headers["Uid"].ToString();

            Expression<Func<MachineBX, bool>> where = (p => p.WXID == wxid);
            MachineBX entity = BLL.GetByWhere(where);

            MachineBXDetail entityDetail = new MachineBXDetail();

            switch (status)
            {
                case "cx"://撤销
                    if (entity.Status != "10")
                    {
                        return Json(new
                        {
                            recode = 0,
                            msg = "维修单不是未处理,撤销失败"
                        });
                    }
                    entity.Status = "40";
                    entity.Del = true;
                    entityDetail.Kind = "30";
                    // entityDetail.WXContent = "撤销";
                    break;
                case "sl"://受理
                    if (entity.Status != "10")
                    {
                        return Json(new
                        {
                            recode = 0,
                            msg = "维修单不是未处理,受理失败"
                        });
                    }
                    entity.Status = "20";
                    entity.Receiver = uid;
                    entity.RecTime = DateTime.Now;
                    entityDetail.Kind = "90";
                    // entityDetail.WXContent = "受理";
                    break;
                case "th"://退回
                    if (entity.Status != "20")
                    {
                        return Json(new
                        {
                            recode = 0,
                            msg = "维修单不是处理中,退回失败"
                        });
                    }
                    entity.Status = "10";
                    entityDetail.Kind = "40";
                    // entityDetail.WXContent = "退回";
                    break;
                case "sc"://删除
                    entity.Del = true;
                    entityDetail.Kind = "50";
                    // entityDetail.WXContent = "删除";
                    break;
                case "hf"://恢复
                    entity.Del = false;
                    entityDetail.Kind = "60";
                    // entityDetail.WXContent = "恢复";
                    break;
                case "jh"://激活
                    if (entity.Status != "30")
                    {
                        return Json(new
                        {
                            recode = 0,
                            msg = "维修单不是已结算,激活失败"
                        });
                    }
                    entity.Status = "20";
                    entityDetail.Kind = "80";
                    // entityDetail.WXContent = "激活";
                    break;
                default:
                    return Json(new
                    {
                        recode = 0,
                        msg = "状态错误"
                    });
            }

            entity.Updater = uid;
            entity.Updatetime = DateTime.Now;

            entityDetail.WXContent = context;
            entityDetail.WXID = wxid;
            entityDetail.Appliant = uid;
            entityDetail.AppTime = DateTime.Now;
            entityDetail.Creater = uid;
            entityDetail.CreateTime = DateTime.Now;
            entityDetail.Updater = uid;
            entityDetail.Updatetime = DateTime.Now;
            entityDetail.GUID = Guid.NewGuid().ToString();

            MachineWXDetailBLL BLLDetail = new MachineWXDetailBLL();
            if (BLL.updateEntity(entity) == 0)
            {
                return Json(new { recode = 0, msg = "状态变更失败" });

            }
            if (!BLLDetail.Add(entityDetail))
            {
                return Json(new { recode = 0, msg = "记录新增失败" });
            }

            return Json(new
            {
                recode = 1,
                msg = "状态变更成功"
            });
        }
    }
}
